package com.xm.rsi.aop;

import com.xm.rsi.annotation.RateLimit;
import com.xm.rsi.common.ErrorCode;
import com.xm.rsi.exception.BusinessException;
import com.xm.rsi.model.entity.User;
import com.xm.rsi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * 接口限流aop
 */
@Slf4j
@Aspect
@Component
public class RateLimitAspect implements Serializable {

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    public static int c = 0;
//    @Resource
//    private UserService userService;

    @Around("@annotation(rateLimit)")
    public Object doRateLimit(ProceedingJoinPoint proceedingJoinPoint, RateLimit rateLimit) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Integer count = redisTemplate.opsForValue().get(request.getRemoteAddr());
        if (count != null && count > rateLimit.rateLimit()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请求过于频繁！");
        }
        redisTemplate.opsForValue().set(request.getRemoteAddr(), count == null ? 1 : count + 1, 2, TimeUnit.SECONDS);
        return proceedingJoinPoint.proceed();
    }
}
